package onion.mqtt.server.processor;


import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.util.AttributeKey;
import onion.mqtt.server.MqttServerConst;
import onion.mqtt.server.MqttServerBuilder;
import onion.mqtt.server.dispatcher.IMqttMessageDispatcher;
import onion.mqtt.server.dispatcher.MqttMessageDispatcher;
import onion.mqtt.server.event.IMqttServerConnectListener;
import onion.mqtt.server.manager.MessageManager;
import onion.mqtt.server.store.MessageStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author Mr, Lu
 * @developmentTeam 浙江允泽信息科技有限公司
 * @createTime 2023/12/12
 */
public class DisConnectProcessor extends AbstractMqttServerProcessor<MqttMessage>{
    static final Logger log = LoggerFactory.getLogger(DisConnectProcessor.class);
    private final IMqttServerConnectListener connectStatusListener;
    private final IMqttMessageDispatcher messageDispatcher;

    public DisConnectProcessor(MqttServerBuilder serverBuilder) {
        this.connectStatusListener = serverBuilder.getConnectListener();
        this.messageDispatcher = new MqttMessageDispatcher();
    }

    @Override
    public void process(Channel channel, MqttMessage message) {
        String clientId = (String) channel.attr(AttributeKey.valueOf(MqttServerConst.CLIENT_ID)).get();
        log.debug("clientId: {} off line!", clientId);

        // 发送遗嘱消息
        List<MessageStore> willMessage = MessageManager.getInstance().getWillMessageByClient(clientId);
        messageDispatcher.dispatchWillMsg(channel, willMessage);

        // 关闭连接
        close(channel);

        // 更新离线状态
        CompletableFuture.runAsync(() -> {
            try {
                if (connectStatusListener!= null) {
                    connectStatusListener.offline(channel, clientId);
                }
            } catch (Throwable e) {
                log.error("disConnect publishEvent error clientId: {}", clientId);
            }
        });
    }
}
